package com.action;

import com.annotation.Lock;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.excel.ExcelUtil;
import com.pojo.*;
import com.pojo.Dictionary;
import com.service.*;
import com.util.PasswordUtil;
import com.util.StringUtil;
import com.util.ValidateHelper;
import com.vo.BusinessStatisticsVo;
import com.vo.BusinessVo;
import com.vo.TrailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/business")
public class BusinessAction {

    @Autowired
    private BusinessService businessService;

    @Autowired
    private StaffService staffService;

    @Autowired
    private TrailService trailService;

    @Autowired
    private DictionaryService dictionaryService;

    @Value("${upload.dir}")
    private String download ;

    @Autowired
    private BusinessStatisticsService businessStatisticsService;

    @Autowired
    private StaffStatisticsService staffStatisticsService;

    /**
     * 商户列表
     * @param name  商户名称
     * @param page  页数
     * @param limit 每页条数
     * @return
     */
    @RequestMapping("/getBusinessList")
    public ResponseBean getBusinessList(String name, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit){
        IPage iPage = businessService.getBusinessList(name, page, limit);
        return new ResponseBean(0,iPage.getTotal(),"成功", iPage.getRecords());
    }


    /**
     * 新增商户
     * @return
     */
    @RequestMapping("/addBusiness")
    @Lock(name = "batchAddBusiness")
    public ResponseBean addBusiness(@RequestBody Business business) {
        business.setCreateTime(new Date());
        business.setStatus(1);
        int c = businessService.selectBh(business.getBh());
        if (c != 0) {
            return new ResponseBean(500, 1, "商户编号已存在");
        }
        int i = businessService.selectBusinessName(business.getName());
        if (i != 0) {
            return new ResponseBean(500, 1, "商户名称已存在");
        }
        business.setPassword(PasswordUtil.jiami("123456"));
        Integer j = businessService.getMaxBh();
        Integer bh = businessService.getBh(j + 1);
        business.setBh(bh);
        if(ValidateHelper.isEmptyString(business.getWyid())) {
            business.setWyid(null);
        }
        if (businessService.save(business)) {
            return new ResponseBean(200, 1, "新增成功");
        }

        return new ResponseBean(500, 1, "新增失败");
    }

    @RequestMapping("/updateBusiness")
    public ResponseBean updateBusiness(@RequestBody Business business){

        int i = businessService.selectBusinessName(business.getName());
        int m = businessService.selectBusinessNameId(business.getName(),business.getId());
        if(i>=1 && m==0){
            return new ResponseBean(500,1,"重复","商户名称重复");
        }
        int j = businessService.selectBh(business.getBh());
        int k = businessService.selectBhId(business.getBh(),business.getId());
        if(j>=1 && k==0){
            return new ResponseBean(500,1,"重复","商户编号重复");
        }
        if (ValidateHelper.isNotEmptyString(business.getMessage())) {
            String message = business.getMessage();
            message = message.replaceAll("<", "[");
            message = message.replaceAll(">", "]");
            business.setMessage(message);
        }
        if(businessService.updateById(business)){
            return new ResponseBean(200,1,"修改成功","修改成功");
        }
        return new ResponseBean(500,1,"修改失败");
    }

    /**
     * 修改商户状态
     */
    @RequestMapping("/upStatus")
    public ResponseBean changeStatus(String id, Integer status) {
        Business business = new Business();
        business.setId(id);
        business.setStatus(status);
        if(businessService.updateById(business)){
            return new ResponseBean(0,1,"修改状态成功");
        }
        return new ResponseBean(1,1,"修改状态失败");
    }

    /**
     * 查询状态为启用的商户
     * @return
     */
    @RequestMapping("/selectBusinessStatus")
    public ResponseBean selectBusinessStatus(){
        List<Business> businessList = businessService.getBusinessList();
        return new ResponseBean(0,1,"查找启用商户",businessList);
    }

    /**
     * 导出Excel
     */
    @RequestMapping("/exportExcelByBusiness")
    public ResponseEntity<InputStreamResource> exportExcelByBusiness(String name) throws IOException {
        if(StringUtil.isNull(name)){
            name=null;
        }
        List<BusinessVo> businessList = businessService.exportByExcel(name);
        String cnFileName = new String("商户记录".getBytes(), "utf-8");
        String name2 = cnFileName + new Date().getTime() + ".xls" ;
        String fileName = download + "/excel/" + name2 ;
        if(!new File(download + "/excel/").exists()) {
            new File(download + "/excel/").mkdirs() ;
        }
        try {
            ExcelUtil.exportExcelByBusiness(fileName,"商户记录",businessList);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        FileSystemResource file = new FileSystemResource (fileName) ;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(name2.getBytes(), "iso-8859-1")));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }

    /**
     * 批量导入员工
     * @param file
     * @return
     */
    @PostMapping(value = "/batchAddBusiness")
    @Lock(name = "batchAddBusiness")
    public ResponseBean batchAddStaff(@RequestParam MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        Map<String, Object> map = new HashMap<>();
        List<Business> businessList = new ArrayList<>();
        Map<String, String> resultMap = ExcelUtil.importExcelByBusiness(fileName, file,businessList);
        if (resultMap.containsKey("error")) {
            return new ResponseBean(500, "失败", resultMap.get("error"));
        }
        if (resultMap.containsKey("sucess")) {
            if (businessService.saveBatch(businessList)) {
                return new ResponseBean(200, "导入成功", businessList);
            }
        }
        return new ResponseBean(500, "失败", "导入失败");
    }

    /**
     * 查询状态为启用的商户
     * @return
     */
    @RequestMapping("/getStaffByCardNo")
    public ResponseBean getStaffByCardNo(String cardNo){
        Staff staff = staffService.getStaffByCardNo(cardNo);
        if (null != staff) {
            staff.setPicture("/upload/" + staff.getPicture());
            return new ResponseBean(200,1,"获取成功",staff);
        }
        return new ResponseBean(500,1,"卡号不存在","卡号不存在");
    }

    /**
     * 获取二维码
     * @param staffId
     * @return
     */
    @RequestMapping("getQrCode")
    public ResponseBean getQrCode(String staffId){
        String color = businessService.getQrCode(staffId);
        return new ResponseBean(200,1,"获取成功",color);
    }

    /**
     * 添加轨迹记录
     * @param type   0 入店  1 出店
     * @return
     */
    @RequestMapping("/addTrail")
    @Lock(name="addTrail")
    public ResponseBean addTrail(String staffBh, Integer type, HttpServletRequest request) {
        Business business = (Business) request.getSession().getAttribute("business");
        if (business == null) {
            return new ResponseBean(500, "商户不存在", "商户不存在");
        }
        Trail trail = new Trail();
        if(type == 0) {
            List<Trail> trailList = trailService.getTrail(staffBh, business.getBh());
            if (ValidateHelper.isNotEmptyCollection(trailList)) {
                Trail trail1 = trailList.get(0);
                List<Dictionary> dicList = dictionaryService.getDicByType("TrailExpTime");
                if (ValidateHelper.isNotEmptyCollection(dicList)) {
                    Dictionary dictionary = dicList.get(0);
                    Integer expTime = Integer.valueOf(dictionary.getCode());
                    Calendar c1=Calendar.getInstance();
                    Calendar c2=Calendar.getInstance();
                    Calendar c3=Calendar.getInstance();
                    c1.setTime(trail1.getRdTime());//要判断的日期
                    c2.setTime(new Date());//初始日期
                    c3.setTime(new Date());//也给初始日期 把分钟加五
                    c3.add(Calendar.MINUTE, expTime);
                    c2.add(Calendar.MINUTE,-expTime);//减去五分钟
                    // 5分钟之内重复
                    if (c1.after(c2)&&c1.before(c3)){
                        System.out.println("重复轨迹");
                        if (trail1.getCdTime() == null) {
                            return new ResponseBean(500, "五分钟之内到过本店", "");
                        }
                    }
                }
            }
            trail.setBusiBh(business.getBh());
            if (ValidateHelper.isNotEmptyString(business.getAddress())) {
                trail.setAddress(business.getAddress());
            }
            trail.setStaffBh(staffBh);
            trail.setRdTime(new Date());
            if (trailService.save(trail)) {
                BusinessStatistics bs = businessStatisticsService.getNowDateBusinessStatistics(business.getId());
                if (null != bs) {
                    bs.setAccess_count(bs.getAccess_count() + 1);
                    businessStatisticsService.updateById(bs);
                }else {
                    bs = new BusinessStatistics();
                    bs.setBusiness_id(business.getId());
                    bs.setBusiness_bh(business.getBh());
                    bs.setBusiness_name(business.getName());
                    bs.setAccess_date(new Date());
                    bs.setAccess_count(1);
                    bs.setWyId(business.getWyid());
                    businessStatisticsService.save(bs);
                }

                Staff staff = staffService.getStaffByBh(trail.getStaffBh());
                staff.setLast_out_time(new Date());
                staffService.updateById(staff);

                //获取员工当天统计记录
                StaffStatistics ss = staffStatisticsService.getNowDateStaffStatistics(staff.getId());
                if (null != ss) {
                    ss.setAccess_count(ss.getAccess_count() + 1);
                    staffStatisticsService.updateById(ss);
                }else {
                    ss = new StaffStatistics();
                    ss.setStaff_id(staff.getId());
                    ss.setStaff_bh(trail.getStaffBh());
                    ss.setStaff_name(staff.getName());
                    ss.setAccess_date(new Date());
                    ss.setAccess_count(1);
                    staffStatisticsService.save(ss);
                }

                try {
                    String codeColor = businessService.getQrCode(staff.getId());
                    if ("red".equals(codeColor)) {

                        // 给所有红码监控人员发送通知和消息
                        /*List<RedControl> redControlList = redCodeControlService.list();
                        if (ValidateHelper.isNotEmptyCollection(redControlList)) {
                            for (RedControl redControl : redControlList) {
                                redpackMsgPushService.sendMessage(staff.getId(), redControl.getStaffId(), "travel_remind", "红码人员:" + staff.getName() + ",出现在商户:" + business.getName());
                            }
                        }*/
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }

                return new ResponseBean(200, "成功", "");
            }

            return new ResponseBean(500, "添加失败", "添加失败");
        }else{
            List<Trail> trailList = trailService.getTrailByStaffBh(staffBh);
            if(trailList.size() == 0) {
                return ResponseBean.error("离店失败") ;
            }else{
                trailList.get(0).setCdTime(new Date());
                trailService.updateById(trailList.get(0)) ;
                return new ResponseBean(200 , "成功" , "") ;
            }
        }
    }

    /**
     * 判断是否是离店
     * @return
     */
    @RequestMapping("get_last_trail")
    public ResponseBean getLastTrail(String staffBh, HttpServletRequest request) {
        Business business = (Business) request.getSession().getAttribute("business");
        if (business == null) {
            return new ResponseBean(500, "商户不存在", "商户不存在");
        }
        List<Trail> trailList = trailService.getTrailByStaffBh(staffBh);
        if(trailList.size() != 0) {
            if(trailList.get(0).getBusiBh().equals(business.getBh()) && trailList.get(0).getCdTime() == null) {
                return new ResponseBean(200 , "" , true) ;
            }
        }
        return new ResponseBean(200 , "" , false) ;
    }

    /**
     * 重置密码
     * @param id
     * @return
     */
    @RequestMapping("/resetPwd")
    public ResponseBean resetPwd(String id) {
        Business business = businessService.getById(id);
        business.setPassword(PasswordUtil.jiami("123456"));
        if (businessService.updateById(business)) {
            return new ResponseBean(200, "密码重置成功", business);
        }
        return new ResponseBean(500, "密码重置失败", "密码重置失败");
    }

    /**
     * 获取物业每天访问量
     * @return
     */
    @RequestMapping("/getWyStatistics")
    public ResponseBean getWyStatistics(String name,
                                        @RequestParam(required = false) String start_time, @RequestParam(required = false) String end_time,
                                        @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit) {
        IPage<BusinessStatisticsVo> iPage = businessStatisticsService.getWyStatisticsList(name, start_time, end_time, page, limit);
        return new ResponseBean(0,iPage.getTotal(),"成功", iPage.getRecords());
    }

    /**
     * 获取商户每天访问量
     * @return
     */
    @RequestMapping("/getBusinessStatistics")
    public ResponseBean getBusinessStatistics(String name, String wyId,
                                              @RequestParam(required = false) String start_time, @RequestParam(required = false) String end_time,
                                              @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit) {
        IPage<BusinessStatisticsVo> iPage = businessStatisticsService.getBusinessStatisticsList(name, start_time, end_time, wyId, page, limit);
        return new ResponseBean(0,iPage.getTotal(),"成功", iPage.getRecords());
    }

    /**
     * 获取员工每天访问量
     * @return
     */
    @RequestMapping("/getStaffStatistics")
    public ResponseBean getStaffStatistics(String name, @RequestParam(required = false) String start_time, @RequestParam(required = false) String end_time,
                                           @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit)  {
        IPage<StaffStatistics> iPage = staffStatisticsService.getStaffStatisticsList(name, start_time, end_time, page, limit);
        return new ResponseBean(0,iPage.getTotal(),"成功", iPage.getRecords());
    }



    /**
     * 商户访问详情导出Excel
     */
    @RequestMapping("/exportExcelByBusinessStatisticsDetail")
    public ResponseEntity<InputStreamResource> exportExcelByBusinessStatisticsDetail(String businessBh, String queryDate) throws IOException, ParseException {
        List<TrailVo> trailVoList =  trailService.getBusinessStatisticsDetailByExport(businessBh, queryDate);
        Business business = businessService.selectBusinessByBh(Integer.valueOf(businessBh));
        String cnFileName = new String((business.getName() + "-商户访问详情记录").getBytes(), "utf-8");
        String name1 = cnFileName + new Date().getTime() + ".xls" ;
        String fileName = download + "/excel/" + name1 ;
        if(!new File(download + "/excel/").exists()) {
            new File(download + "/excel/").mkdirs() ;
        }
        try {
            businessStatisticsService.exportExcelByBusinessStatisticsDetail(fileName,"商户访问详情记录",trailVoList);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        FileSystemResource file = new FileSystemResource (fileName) ;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(name1.getBytes(), "iso-8859-1")));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }

    /**
     * 物业访问量导出Excel
     */
    @RequestMapping("/exportExcelByWyStatistics")
    public ResponseEntity<InputStreamResource> exportExcelByWyStatistics(String name, String start_time, String end_time) throws IOException {
        List<BusinessStatisticsVo> businessStatisticsList =  businessStatisticsService.getWyStatisticsByExport(name,start_time,end_time);
        String cnFileName = new String("物业访问记录".getBytes(), "utf-8");
        String name1 = cnFileName + new Date().getTime() + ".xls" ;
        String fileName = download + "/excel/" + name1 ;
        if(!new File(download + "/excel/").exists()) {
            new File(download + "/excel/").mkdirs() ;
        }
        try {
            businessStatisticsService.exportExcelByWyStatistics(fileName,"物业访问记录",businessStatisticsList);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        FileSystemResource file = new FileSystemResource (fileName) ;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(name1.getBytes(), "iso-8859-1")));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }

    /**
     * 商户访问量导出Excel
     */
    @RequestMapping("/exportExcelByBusinessStatistics")
    public ResponseEntity<InputStreamResource> exportExcelByBusinessStatistics(String name, String start_time, String end_time,String wyId) throws IOException {
        List<BusinessStatisticsVo> businessStatisticsList =  businessStatisticsService.getBusinessStatisticsByExport(name,start_time,end_time,wyId);
        String cnFileName = new String("商户访问记录".getBytes(), "utf-8");
        String name1 = cnFileName + new Date().getTime() + ".xls" ;
        String fileName = download + "/excel/" + name1 ;
        if(!new File(download + "/excel/").exists()) {
            new File(download + "/excel/").mkdirs() ;
        }
        try {
            businessStatisticsService.exportExcelByBusinessStatistics(fileName,"商户访问记录",businessStatisticsList);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        FileSystemResource file = new FileSystemResource (fileName) ;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(name1.getBytes(), "iso-8859-1")));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }

    /**
     * 员工访问量导出Excel
     */
    @RequestMapping("/exportExcelByStaffStatistics")
    public ResponseEntity<InputStreamResource> exportExcelByStaffStatistics(String name, String start_time, String end_time) throws IOException {
        List<StaffStatistics> staffStatisticsList =  staffStatisticsService.getStaffStatisticsByExport(name,start_time,end_time);
        String cnFileName = new String("员工访问记录".getBytes(), "utf-8");
        String name1 = cnFileName + new Date().getTime() + ".xls" ;
        String fileName = download + "/excel/" + name1 ;
        if(!new File(download + "/excel/").exists()) {
            new File(download + "/excel/").mkdirs() ;
        }
        try {
            staffStatisticsService.exportExcelByStaffStatistics(fileName,"员工访问记录",staffStatisticsList);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        FileSystemResource file = new FileSystemResource (fileName) ;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(name1.getBytes(), "iso-8859-1")));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }

}
